package com.yangyang.androidconnect.util;

import android.os.Environment;

import com.alibaba.fastjson.JSONObject;
import com.yangyang.androidconnect.common.ApiResult;
import com.yangyang.androidconnect.vo.response.FileInfo;
import com.yanzhenjie.andserver.framework.body.StreamBody;
import com.yanzhenjie.andserver.http.HttpRequest;
import com.yanzhenjie.andserver.http.HttpResponse;
import com.yanzhenjie.andserver.http.ResponseBody;
import com.yanzhenjie.andserver.util.MediaType;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class ResponseFileUtil {
    public static ApiResult getPhotoAlbumListResponse(int page, int pageSize, boolean showHidden) throws Exception {
        List<File> fileList = DCIMFileUtil.getDCIMFilesSortedByDate();

        File dcimDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);

        // 获取 DCIM 目录的绝对路径
        String homePath = dcimDir.getParentFile().getAbsolutePath();


        List<FileInfo> list = new ArrayList<>(fileList.size());
        final String pattern = "yyyy-MM-dd HH:mm:ss";
        for (File f : fileList) {
            String name = f.getName();
            if (!showHidden && name.startsWith(".")) {
                continue;
            }
            // 获取文件的绝对路径
            String filePath = f.getAbsolutePath();

            FileInfo info = new FileInfo();
            info.setIsFile(f.isFile());

            // 确保文件路径是以 DCIM 目录开头的
            if (filePath.startsWith(homePath)) {
                // 截取相对路径部分
                String relativePath = filePath.substring(homePath.length() + 1); // +1 是为了去掉开头的 "/"
                info.setName(relativePath);
            }
            //info.setFullName(filePath);

            BasicFileAttributes attributes = Files.readAttributes(Paths.get(f.getAbsolutePath()), BasicFileAttributes.class);
            Instant creationTime = attributes.creationTime().toInstant();
            Instant lastModifiedTime = attributes.lastModifiedTime().toInstant();

            System.out.println("Creation Time: " + creationTime);
            System.out.println("Last Modified Time: " + lastModifiedTime);

            String formattedCreationTime = DateFormatUtils.format(creationTime.toEpochMilli(), pattern);
            String formattedLastModifiedTime = DateFormatUtils.format(lastModifiedTime.toEpochMilli(), pattern);

            info.setCreationTime(formattedCreationTime);
            info.setLastModifiedTime(formattedLastModifiedTime);
            list.add(info);
        }

        // 计算分页
        int total = list.size();
        int fromIndex = (page - 1) * pageSize;
        int toIndex = Math.min(fromIndex + pageSize, total);

        // 确保分页参数合法
        if (fromIndex >= total || fromIndex < 0) {
            list = Collections.emptyList();
        } else {
            list = list.subList(fromIndex, toIndex);
        }

        JSONObject json = new JSONObject();
        json.put("list", list);
        json.put("path", "file.getAbsoluteFile()");
        json.put("total", total);
        json.put("page", page);
        json.put("pageSize", pageSize);

        return ApiResult.ok(json);
    }

    public static ApiResult getFileListResponse(String path, int page, int pageSize, boolean showHidden) throws Exception {
        File file = FileUtils.getFile(path);
        File[] listFiles = file.listFiles();

        // 按照文件的最后修改时间（通常表示创建时间）降序排序
        Arrays.sort(listFiles, new Comparator<File>() {
            @Override
            public int compare(File f1, File f2) {
                return Long.compare(f2.lastModified(), f1.lastModified());
            }
        });

        List<FileInfo> list = new ArrayList<>(listFiles.length);
        final String pattern = "yyyy-MM-dd HH:mm:ss";
        for (File f : listFiles) {
            String name = f.getName();
            if (!showHidden && name.startsWith(".")) {
                continue;
            }
            FileInfo info = new FileInfo();
            info.setIsFile(f.isFile());
            info.setName(f.getName());
            info.setFullName(f.getAbsolutePath());

            BasicFileAttributes attributes = Files.readAttributes(Paths.get(f.getAbsolutePath()), BasicFileAttributes.class);
            Instant creationTime = attributes.creationTime().toInstant();
            Instant lastModifiedTime = attributes.lastModifiedTime().toInstant();

            System.out.println("Creation Time: " + creationTime);
            System.out.println("Last Modified Time: " + lastModifiedTime);

            String formattedCreationTime = DateFormatUtils.format(creationTime.toEpochMilli(), pattern);
            String formattedLastModifiedTime = DateFormatUtils.format(lastModifiedTime.toEpochMilli(), pattern);

            info.setCreationTime(formattedCreationTime);
            info.setLastModifiedTime(formattedLastModifiedTime);
            list.add(info);
        }

        // 计算分页
        int total = list.size();
        int fromIndex = (page - 1) * pageSize;
        int toIndex = Math.min(fromIndex + pageSize, total);

        Collections.sort(list, new Comparator<FileInfo>() {
            @Override
            public int compare(FileInfo fileInfo, FileInfo t1) {
                if (fileInfo.getIsFile() && t1.getIsFile()) {
                    //文件按照时间到排序
                    int compare = t1.getCreationTime().compareTo(fileInfo.getCreationTime());
                    return compare;
                } else {
                    if (fileInfo.getIsFile() || t1.getIsFile()) {
                        //目录华为文件，目录排在文件前面
                        int i = fileInfo.getIsFile().compareTo(t1.getIsFile());
                        return i;
                    } else {
                        //如果都是目录，目录按名称排序
                        int i = fileInfo.getName().compareTo(t1.getName());
                        return i;
                    }

                }
            }
        });

        // 确保分页参数合法
        if (fromIndex >= total || fromIndex < 0) {
            list = Collections.emptyList();
        } else {
            list = list.subList(fromIndex, toIndex);
        }

        JSONObject json = new JSONObject();
        json.put("list", list);
        json.put("path", file.getAbsoluteFile());
        json.put("total", total);
        json.put("page", page);
        json.put("pageSize", pageSize);

        return ApiResult.ok(json);
    }

    public static ResponseBody file(String path, HttpResponse response) throws IOException {
        File file = FileUtils.getFile(path);
        String extension = FilenameUtils.getExtension(file.getAbsolutePath()).toLowerCase();
        String mimeType = "";
        boolean isFileName = false;
        switch (extension) {
            case "text":
                mimeType = MediaType.TEXT_EVENT_STREAM_VALUE;
                break;
            case "gif":
                mimeType = MediaType.IMAGE_GIF_VALUE;
                break;
            case "jpeg":
            case "jpg":
                mimeType = MediaType.IMAGE_JPEG_VALUE;
                break;
            case "png":
                mimeType = MediaType.IMAGE_PNG_VALUE;
                break;
            case "pdf":
                mimeType = MediaType.APPLICATION_PDF_VALUE;
                break;
            case "mp4":
                mimeType = "video/mp4";
                break;
            default:
                mimeType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
                isFileName = true;
                break;
        }

        FileInputStream fileInputStream = FileUtils.openInputStream(file);
        //long totalBytes = FileUtils.sizeOf(file);
        String fileName = FilenameUtils.getName(file.getAbsolutePath());
        if (isFileName) response.addHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
        response.addHeader("Content-Type", mimeType);

        StreamBody streamBody = new StreamBody(fileInputStream);
        return streamBody;
    }

    public static ResponseBody streamFile(String path, HttpRequest request, HttpResponse response) throws IOException {
        String normalize = FilenameUtils.normalize(path);

        FileInputStream fileInputStream = FileUtils.openInputStream(FileUtils.getFile(path));
        //long totalBytes = FileUtils.sizeOf(file);
        //String fileName = FilenameUtils.getName(normalize);
        //response.addHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
        response.addHeader("Content-Type", MediaType.APPLICATION_OCTET_STREAM_VALUE);

        StreamBody streamBody = new StreamBody(fileInputStream);
        return streamBody;
    }
}
